import Request from 'luch-request'

import api from '@/config/api'
import storage from '@/utils/storage'

let isNavigateTo = false

const http = new Request()

http.setConfig((config) => {
  config.baseURL = api.buyer
  config.header = {
    ...config.header
  }

  return config
})

http.interceptors.request.use(
  (config) => {
    config.header = {
      ...config.header
    }
    if (config.params) {
      for (const [key, value] of Object.entries(config.params)) {
        if (value === undefined || value === null || value === '')
          delete config.params[key]
      }
    }
    if (config.data) {
      for (const [key, value] of Object.entries(config.data)) {
        if (value === undefined || value === null || value === '')
          delete config.data[key]
      }
    }

    config.header = {
      ...config.header
    }
    return config
  },
  (config) => {
    return Promise.reject(config)
  }
)

// 是否正在刷新的标记
let isRefreshing = false
// 重试队列
let requests: any = []
// 必须使用异步函数，注意
http.interceptors.response.use(
  async (response) => {
    isNavigateTo = false

    if (
      (response.statusCode === 200 && !response.data.success) ||
      response.statusCode === 400
    ) {
      if (response.data.message) {
        uni.showToast({
          title: response.data.message,
          icon: 'none'
        })
      }
    }
    return response
  },
  (error) => {
    return error
  }
)

export { http }

interface MethodFace {
  [key: string]: string
}

export const Method: MethodFace = {
  GET: 'GET',
  POST: 'POST',
  PUT: 'PUT',
  DELETE: 'DELETE'
}
